﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using FastDFS.Client;
using FastDFS.WinForm.Models;

namespace FastDFS.WinForm.Forms
{
    public partial class FileSvnForm : Form
    {
        private List<IPEndPoint> trackerIPs =new List<IPEndPoint>();
        private IPEndPoint endPoint;
        private StorageNode node;

        protected string masterfdfsname;
        protected Dictionary<string,FDFSFileInfo> fdfsInfors=new Dictionary<string, FDFSFileInfo>();
        private FDFSTableDataContext fdfsContext = LocalDataContextFactory.getFDFSDataContext();

        public FileSvnForm():base()
        {
            InitializeComponent();
            
           
            endPoint = new IPEndPoint(IPAddress.Parse(AppConfig.DFS_TRACKER_HOST), 22122);
            trackerIPs.Add(endPoint);
        }

        protected void initDFS(params string[] groupNames)
        {

            
            ConnectionManager.Initialize(trackerIPs);
            if (groupNames.Length > 0&&!string.IsNullOrWhiteSpace(groupNames[0]))
            {
                node = FastDFSClient.GetStorageNode(groupNames[0]);
            }
            else
            {
                node = FastDFSClient.GetStorageNode();
            }
        }

      
        private void updateInfo(string pattern, params object[] vals)
        {
            toolStripStatusLabel1.Text = string.Format(pattern, vals);
        }

        private void updateFileInfo()
        {
            lvFileInfo.Items.Clear();
            foreach (var fdfsname in fdfsInfors.Keys)
            {

                ListViewItem lvi=new ListViewItem();
                FDFSFileInfo fileInfo = fdfsInfors[fdfsname];
                string ver = fdfsname.Substring(masterfdfsname.LastIndexOf("."));
                
                if(ver.Contains("."))
                    ver = ver.Substring(0, ver.LastIndexOf("."));
                
                if(string.IsNullOrWhiteSpace(ver))
                {
                    ver = "master";
                }
                lvi.Text = ver;
                //lvi.SubItems.Add(ver);
                lvi.SubItems.Add(fdfsname);
                lvi.SubItems.Add(fileInfo.FileSize+"kb");
                lvi.SubItems.Add(fileInfo.CreateTime.ToString("G"));
                lvi.SubItems.Add(fileInfo.Crc32.ToString());
                lvFileInfo.Items.Add(lvi);
            }
        }

        private void checkMasterFile()
        {
            if (string.IsNullOrWhiteSpace(masterfdfsname))
            {
                throw new Exception();
            }
        }

        private void btnUploadMaster_Click(object sender, EventArgs e)
        {
             DialogResult dre = ofdUploadMaster.ShowDialog();
            if (dre != DialogResult.OK)
            {
                return;
                updateInfo("以选中个{0}文件，请点击上传", ofdUploadMaster.FileNames.Length);
            }
            else
            {
                dre = MessageBox.Show("已选中" + ofdUploadMaster.FileNames.Length + " 个文件,是否马上上传?", "上传文件", MessageBoxButtons.OKCancel);
                if (dre != DialogResult.OK) return;
            }



            initDFS(tbUploadGroupName.Text);
            updateInfo("upload starting "+tbUploadGroupName.Text+"...");
            DateTime start = DateTime.Now;
            string msg = "file list \n";
            string f = ofdUploadMaster.FileName;
           // ofdUploadMaster.FileNames.AsParallel().ForAll(f =>
           // {
                string key = FastDFSClient.UploadFile(node, f)[0], ext = Path.GetExtension(f);

                FDFSFileInfo fileInfo = FastDFSClient.GetFileInfo(node, key);
                fdfsInfors.Add(key,fileInfo);
                
                //string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb");
                //string key = FastDFSClient.UploadFile(node, content, ext);
                msg += string.Format("file:{0}\nkey:{1}\n\n", f, key);
                masterfdfsname = key;

                attachment attachment = new attachment
                {
                    fdfs_key = key
                    ,
                    fdfs_upload_at = DateTime.Now
                    ,
                    file_name = f
                    ,
                    file_ext = ext
                    ,
                    file_size = (int)fileInfo.FileSize

                };
                
               // fdfsContext.attachments.InsertOnSubmit(attachment);
               // fdfsContext.SubmitChanges();
           // });

            DateTime end = DateTime.Now;
            TimeSpan consume = ((TimeSpan)(end - start));
            double consumeSeconds = Math.Ceiling(consume.TotalSeconds);
            updateInfo("upload finish....{0}", consumeSeconds);
            updateFileInfo();

            lbMasterFileInfo.Text = string.Format("masertfdfsname:  {0}\nfilename: {1}",masterfdfsname,f);
            string url = string.Format("http://{0}:{1}/{2}/{3}"
                ,node.EndPoint.Address
                ,80
                ,tbUploadGroupName.Text
                ,masterfdfsname
                );
            linkDonwloadMasterFile.Text = url;
            
            MessageBox.Show(msg);
        }

        private void btnUploadSlave_Click(object sender, EventArgs e)
        {
            checkMasterFile();

            if (string.IsNullOrWhiteSpace(tbSlaverPrefix.Text))
            {
                MessageBox.Show("版本号不能为空");
                return;
            }

            DialogResult dre = ofdUploadSlave.ShowDialog();
            if (dre != DialogResult.OK)
            {
                return;
                updateInfo("以选中个{0}文件，请点击上传", ofdUploadMaster.FileNames.Length);
            }
            else
            {
                dre = MessageBox.Show("已选中" + ofdUploadSlave.FileNames.Length + " 个文件,是否马上上传?", "上传文件", MessageBoxButtons.OKCancel);
                if (dre != DialogResult.OK) return;
            }



            initDFS(tbUploadGroupName.Text);
            updateInfo("upload starting " + tbUploadGroupName.Text + "...");
            DateTime start = DateTime.Now;
            string msg = "file list \n",f=ofdUploadSlave.FileName;
           // ofdUploadSlave.FileNames.AsParallel().ForAll(f =>
           // {
                //string key = //FastDFSClient.UploadSlaveFile(tbUploadGroupName.Text, f)[0], ext = Path.GetExtension(f);
                string key = "",ext=Path.GetExtension(f).TrimStart('.');
            FDFSFileInfo fileInfo;    
            using (FileStream fs= new FileStream(f, FileMode.Open))
            {
                long size = fs.Length;
                    key = FastDFSClient.UploadSlaveFile(tbUploadGroupName.Text, fs, masterfdfsname,
                        tbSlaverPrefix.Text,ext);
                     fileInfo = new FDFSFileInfo()
                    {
                        Crc32 = 0,
                        CreateTime = DateTime.Now
                        ,
                        FileSize = size                    };
                    fdfsInfors.Add(key, fileInfo);
                }
               
                //FDFSFileInfo fileInfo = FastDFSClient.GetFileInfo(node, key);
                //fdfsInfors.Add(key, fileInfo);
               
                //string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb");
                //string key = FastDFSClient.UploadFile(node, content, ext);
                msg += string.Format("file:{0}\nkey:{1}\n\n", f, key);
               

                attachment attachment = new attachment
                {
                    fdfs_key = key
                    ,
                    fdfs_upload_at = DateTime.Now
                    ,
                    file_name = f
                    ,
                    file_ext = ext
                    ,
                    file_size = (int)fileInfo.FileSize

                };

                // fdfsContext.attachments.InsertOnSubmit(attachment);
                // fdfsContext.SubmitChanges();
           // });

            DateTime end = DateTime.Now;
            TimeSpan consume = ((TimeSpan)(end - start));
            double consumeSeconds = Math.Ceiling(consume.TotalSeconds);
            updateInfo("upload finish....{0}", consumeSeconds);
            updateFileInfo();
            MessageBox.Show(msg);

        }

       

        private void btnQueryFileInfo_Click(object sender, EventArgs e)
        {
            checkMasterFile();

            if (string.IsNullOrWhiteSpace(tbManageSlavePrefix.Text))
            {
                MessageBox.Show("版本号不能为空");
                return;
            }
              initDFS();
            
            FDFSFileInfo fdfsFileInfo = FastDFSClient.GetSlaveFileInfo(node, masterfdfsname,tbManageSlavePrefix.Text);
            lbSlaveFileInfo.Text = string.Format("fdfsname: {0}\n filesize: {1}\n create time: {2}\n crc32: {3}"
                ,fdfsFileInfo.FdfsName
                ,fdfsFileInfo.FileSize
                ,fdfsFileInfo.CreateTime.ToString("G")
                ,fdfsFileInfo.Crc32
                );

        }

        private void btnDeleteSlave_Click(object sender, EventArgs e)
        {
            checkMasterFile();

            if (string.IsNullOrWhiteSpace(tbManageSlavePrefix.Text))
            {
                MessageBox.Show("版本号不能为空");
                return;
            }
            initDFS();
            string fdfsname = FastDFSClient.RemoveSlaveFile(tbUploadGroupName.Text,masterfdfsname,tbManageSlavePrefix.Text);
            MessageBox.Show(string.Format("成功删除 {0}", fdfsname));
        }

        private void linkDonwloadMasterFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            LinkLabel ll = (LinkLabel) sender;
            System.Diagnostics.Process.Start(ll.Text);
        }

        
    }
}
